package com.feel.mall.userservice.controller;

import com.feel.mall.common.bean.Collect;
import com.feel.mall.common.bean.RespBean;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.CollectService;
import com.feel.mall.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author: 刘永钦
 * @Description:
 */
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;

    /**
     * 添加--收藏
     */
    @PostMapping("/{goodsId}")
    public RespBean addInfo(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) throws FeelException {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer id = (Integer) map.get("id");

        Collect collect = new Collect();
        collect.setUserId(id);
        collect.setGoodsId(goodsId);

        // 添加
        return collectService.addInfo(collect) ? RespBean.ok("添加成功") : RespBean.error("添加失败");
    }

    /**
     * 删除--取消收藏
     */
    @DeleteMapping("/{id}")
    public RespBean delInfo(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws FeelException {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

         return collectService.delInfo(id, userId) ? RespBean.ok("取消成功") : RespBean.error("取消失败");
    }

    /**
     * 根据商品id和用户id查询收藏
     */
    @GetMapping("/{goodsId}")
    public RespBean getInfo(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        Collect collect = collectService.getByGoodsIdAndUserId(goodsId, userId);

        return RespBean.ok("查询成功", collect);
    }

    /**
     * 获取收藏列表
     */
    @GetMapping
    public RespBean getList( @RequestHeader("token") String token) {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        Collect condition = new Collect();
        condition.setUserId(userId);
        List<Collect> list = (List<Collect>) collectService.getAllByCondition(condition, null, null);

        return RespBean.ok("查询成功",list);
    }
}
